import CodoBase from "../../../lib/CodoBase";
import CodoError from "../../../lib/CodoError";
import { Wechat } from "../wechat";

/**
 * 公众号消息管理接口
 *
 */
export default class CodoWechatGzhMessage extends CodoBase {
	/**
	 * 发送模板消息
	 * - https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Template_Message_Interface.html#%E5%8F%91%E9%80%81%E6%A8%A1%E6%9D%BF%E6%B6%88%E6%81%AF
	 */
	async sendTemplateMessage(message: Wechat.gzh.request.IMessageData, accessToken?: string) {
		accessToken = accessToken || this.app.codo.wechat.gzh.accessToken.getCurrentContextCacheAccessToken();

		const url = `https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=${accessToken}`;

		// 发送的消息必须先自行json.stringify 否则会出现47001格式错误。
		const sendData = JSON.stringify(message);
		const res = await this.app.curl<Wechat.ICommonRespnose & { msgid: string }>(url, {
			method: "POST",
			dataType: "json",
			data: sendData,
		});

		if (res.data.errcode) {
			throw new CodoError(`wechat gzh send template message error %s %s`, res.data.errcode, res.data.errmsg);
		}
		return res.data;
	}

	/** 获取gzh模板消息的列表 */
	async getMessageTemplateList(accessToken?: string) {
		accessToken = accessToken || this.app.codo.wechat.gzh.accessToken.getCurrentContextCacheAccessToken();

		const url = `https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token=${accessToken}`;
		const res = await this.app.curl<Wechat.ICommonRespnose & Wechat.gzh.response.IMessageTemplateList>(url, {
			method: "GET",
			dataType: "json",
		});

		if (res.data.errcode) {
			throw new CodoError(`wechat gzh getMessageTemplateList error %s %s`, res.data.errcode, res.data.errmsg);
		}

		return res.data;
	}
}
